package com.xihuanjun.sdk.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;

public class JsonUtils {

    public static String map2json(Map<String,Object> map){
        ObjectMapper mapper=new ObjectMapper();
        String jsonStr= null;
        try {
            jsonStr = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return jsonStr;
    }

    public static HashMap json2map(String json){
        ObjectMapper mapper=new ObjectMapper();
        HashMap map= null;
        try {
            map = mapper.readValue(json, HashMap.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return map;
    }

    public static <T> T json2Object(String json,Class<T> tClass) {
        ObjectMapper objectMapper=new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
        T t = null;
        try {
            t = objectMapper.readValue(json, tClass);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return t;
    }





    public static String object2Json(Object o){
        ObjectMapper objectMapper=new ObjectMapper();
        String s = null;
        try {
            s = objectMapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return s;
    }
}
